package me.aartikov.alligator.converters;


import me.aartikov.alligator.AbilityResult;
import me.aartikov.alligator.ScreenResult;
import ohos.aafwk.content.Intent;
import ohos.utils.Sequenceable;

import java.io.Serializable;

import static me.aartikov.alligator.AbilityResult.RESULT_OK;


/**
 * Creates {@code ActivityResult(Activity.RESULT_OK, data)} (where {@code data} contains a serialized screen result) if a screen result is not {@code null},
 * and {@code ActivityResult(Activity.RESULT_CANCELED, null)} otherwise.
 *
 * @param <ScreenResultT> screen result type
 */

public class DefaultScreenResultConverter<ScreenResultT extends ScreenResult> implements ScreenResultConverter<ScreenResultT> {
    private static final String KEY_SCREEN_RESULT = "me.aartikov.alligator.KEY_SCREEN_RESULT";

    private Class<ScreenResultT> mScreenResultClass;

    public DefaultScreenResultConverter(Class<ScreenResultT> screenResultClass) {
        mScreenResultClass = screenResultClass;
    }

    @Override

    public AbilityResult createActivityResult(ScreenResultT screenResult) {
        Intent data = new Intent();
        if (screenResult instanceof Serializable) {
            data.setParam(KEY_SCREEN_RESULT, (Serializable) screenResult);
        } else if (screenResult instanceof Sequenceable) {
            data.setParam(KEY_SCREEN_RESULT, (Sequenceable) screenResult);
        } else {
            throw new IllegalArgumentException("Screen result " + screenResult.getClass().getCanonicalName() + " should be Serializable or Parcelable.");
        }
        return new AbilityResult(RESULT_OK, data);
    }

    @SuppressWarnings("unchecked")
    @Override

    public ScreenResultT getScreenResult(AbilityResult activityResult) {
        try {
            if (activityResult.getIntent() == null || activityResult.getResultCode() != RESULT_OK) {
                return null;
            } else if (Serializable.class.isAssignableFrom(mScreenResultClass)) {
                return (ScreenResultT) activityResult.getIntent().getParams().getParam(KEY_SCREEN_RESULT);
            } else if (Sequenceable.class.isAssignableFrom(mScreenResultClass)) {
                return (ScreenResultT) activityResult.getIntent().getParams().getParam(KEY_SCREEN_RESULT);
            } else {
                throw new IllegalArgumentException("Screen result " + mScreenResultClass.getCanonicalName() + " should be Serializable or Parcelable.");
            }
        } catch (Exception e) {
            return null;
        }
    }
}
